package mi.payment.ui.print.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Locale;

import io.github.suzp1984.jbig.JbigCodec;
import io.github.suzp1984.jbig.JbigCodecFactory;
import mi.payment.BuildConfig;
import mi.payment.R;
import mi.payment.constants.BankInfo;
import mi.payment.constants.CARDTYPE;
import mi.payment.constants.Configs;
import mi.payment.constants.CurrencyInfo;
import mi.payment.constants.TransType;
import mi.payment.controller.BaseQpsSettingController;
import mi.payment.ui.print.helper.PrintController;
import mi.payment.controller.QpsSettingController;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.QPSParamsOperation;
import mi.payment.settings.SalesSlipPrintSettings;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.utils.MoneyUtils;
import mi.payment.utils.NumberUtil;
import mi.payment.utils.SystemDateTime;
import mi.payment.utils.iso8583.Utils;
import mi.payment.utils.print.DataPrinterKernel;

/**
 * Created by longx on 2017/5/19.
 */

public class PrintCardView1 extends LinearLayout {

    private View view;
    private Context mContext;
    private TextView subtitle, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20, t21, t22, t23, t24, t25, t26, t27, t28, t29, t30, t31, t32, t33, t34, t35, t36, t37, t38, tCardholderName, t39, t40, t41, t42, t43, t44, t45, t46, t47, t48, t49, t50, t51, t52, t53, t54;
    private ImageView esign_iv;
    private TextView no_Psw_Sign;
    private TextView tvAboutInfo;
    private TextView original_flag;
    private ImageView headLogo;
    boolean isPrintEnglish;
    private SalesSlipPrintSettingsOperation sspsOperation;
    private SalesSlipPrintSettings salesSlipPrintSettings;
    private BaseQpsSettingController qpsSettingController;
    private PrintController printController;

    public PrintCardView1(Context context) {
        super(context);
        mContext = context;
        initView();
    }

    public PrintCardView1(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
    }

    public PrintCardView1(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    private void initView() {
        sspsOperation = SalesSlipPrintSettingsOperation.getInstance();
        isPrintEnglish = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings().isSalesSlipPrintEnglish();
        salesSlipPrintSettings = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings();
        qpsSettingController = new QpsSettingController(null);
        printController = new PrintController();

        view = View.inflate(mContext, R.layout.view_print_card1, this);
        headLogo = (ImageView) view.findViewById(R.id.logo);
        subtitle = (TextView) view.findViewById(R.id.subtitle);
        t1 = (TextView) view.findViewById(R.id.t1);
        t2 = (TextView) view.findViewById(R.id.t2);
        t3 = (TextView) view.findViewById(R.id.t3);
        t4 = (TextView) view.findViewById(R.id.t4);
        t5 = (TextView) view.findViewById(R.id.t5);
        t6 = (TextView) view.findViewById(R.id.t6);
        t7 = (TextView) view.findViewById(R.id.t7);
        t8 = (TextView) view.findViewById(R.id.t8);
        t9 = (TextView) view.findViewById(R.id.t9);
        t10 = (TextView) view.findViewById(R.id.t10);
        t11 = (TextView) view.findViewById(R.id.t11);
        t12 = (TextView) view.findViewById(R.id.t12);
        t13 = (TextView) view.findViewById(R.id.t13);
        t14 = (TextView) view.findViewById(R.id.t14);
        t15 = (TextView) view.findViewById(R.id.t15);
        t16 = (TextView) view.findViewById(R.id.t16);
        t17 = (TextView) view.findViewById(R.id.t17);
        t18 = (TextView) view.findViewById(R.id.t18);
        t19 = (TextView) view.findViewById(R.id.t19);
        t20 = (TextView) view.findViewById(R.id.t20);
        t21 = (TextView) view.findViewById(R.id.t21);
        t22 = (TextView) view.findViewById(R.id.t22);
        t23 = (TextView) view.findViewById(R.id.t23);
        t24 = (TextView) view.findViewById(R.id.t24);
        t25 = (TextView) view.findViewById(R.id.t25);
        t26 = (TextView) view.findViewById(R.id.t26);
        t27 = (TextView) view.findViewById(R.id.t27);
        t28 = (TextView) view.findViewById(R.id.t28);
        t29 = (TextView) view.findViewById(R.id.t29);
        t30 = (TextView) view.findViewById(R.id.t30);
        t31 = (TextView) view.findViewById(R.id.t31);
        t32 = (TextView) view.findViewById(R.id.t32);
        t33 = (TextView) view.findViewById(R.id.t33);
        t34 = (TextView) view.findViewById(R.id.t34);
        t35 = (TextView) view.findViewById(R.id.t35);
        tCardholderName = (TextView) view.findViewById(R.id.tCardholderName);
        t36 = (TextView) view.findViewById(R.id.t36);
        t37 = (TextView) view.findViewById(R.id.t37);
        t38 = (TextView) view.findViewById(R.id.t38);
        t39 = (TextView) view.findViewById(R.id.t39);
        t40 = (TextView) view.findViewById(R.id.t40);
        t41 = (TextView) view.findViewById(R.id.t41);
        t42 = (TextView) view.findViewById(R.id.t42);
        t43 = (TextView) view.findViewById(R.id.t43);
        t44 = (TextView) view.findViewById(R.id.t44);
        t45 = (TextView) view.findViewById(R.id.t45);
        t46 = (TextView) view.findViewById(R.id.t46);
        t47 = (TextView) view.findViewById(R.id.t47);
        t48 = (TextView) view.findViewById(R.id.t48);
        esign_iv = (ImageView) view.findViewById(R.id.esign_iv);
        t49 = (TextView) view.findViewById(R.id.t49);
        t50 = (TextView) view.findViewById(R.id.t50);
        t51 = (TextView) view.findViewById(R.id.t51);
        t52 = (TextView) view.findViewById(R.id.t52);
        t53 = (TextView) view.findViewById(R.id.t53);
        t54 = (TextView) view.findViewById(R.id.t54);
        no_Psw_Sign = (TextView) view.findViewById(R.id.no_Psw_Sign);
        tvAboutInfo = (TextView) view.findViewById(R.id.tv_about_info);
        original_flag = (TextView) view.findViewById(R.id.original_flag);
        tvAboutInfo.setText(DataPrinterKernel.INSTANCE().getSmallTicketTail());

        // 小米的在补打上笔凭证界面,要多加一条分割线
        View dividerTerminalView = view.findViewById(R.id.tv_divider_terminal);
        if ("xiaoMi".equals(BuildConfig.FLAVOR)) {
            dividerTerminalView.setVisibility(View.VISIBLE);
        } else {
            dividerTerminalView.setVisibility(View.GONE);
        }
    }

    public void show(PayDetail payDetail) {
        printHead();

        String title = " ";

        if (!printController.isPrintSubtitle()) {
            subtitle.setVisibility(View.GONE);
        }

        StringBuilder sb = new StringBuilder();

        sb = isPrintEnglish ? sb.append(getString(R.string.bussines_receipt_e)) : sb.append(getString(R.string.bussines_receipt));

        t1.setText(sb.toString());
        sb.setLength(0);

        t2.setText(getString(R.string.receipt_keep_receipt));

        String merchantName = TextUtils.isEmpty(payDetail.tempMerchantName) ? payDetail.merchantName : payDetail.tempMerchantName;
        t3.setText(getString(R.string.receipt_3) + merchantName);


        String merchantNo = TextUtils.isEmpty(payDetail.tempMerchantNo) ? payDetail.merchantNo : payDetail.tempMerchantNo;

        t5.setText(getString(R.string.receipt_4) + merchantNo);

        String terminalNo = TextUtils.isEmpty(payDetail.tempTerminalNo) ? payDetail.terminalNo : payDetail.tempTerminalNo;

        t7.setText(getString(R.string.receipt_5) + terminalNo);
        t9.setText(getString(R.string.receipt_20) + payDetail.operatorNo);
        SalesSlipPrintSettings salesSlipPrintSettings = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings();
        String issuingBank; // 发卡行
        String cardBank = Configs.getInstance().ACQUIRER_DEFAULT_PRINT();    // 收单行
        String caq = payDetail.acquiringBankCode.trim();
        if (!TextUtils.isEmpty(caq)) {
            if (salesSlipPrintSettings.isAcquiringBankPrintChinese()) {
                cardBank = BankInfo.getName(caq);
            } else {
                cardBank = BankInfo.getCode(caq);
            }
        }
        cardBank = cardBank.trim();
        if (salesSlipPrintSettings.issuingBankPrintChinese()) {
            issuingBank = BankInfo.getName(payDetail.issuingBankCode.trim());
        } else {
            issuingBank = BankInfo.getCode(payDetail.issuingBankCode.trim());
        }
        issuingBank = issuingBank.trim();

        t11.setText(getString(R.string.f_bank, issuingBank));
        t13.setText(getString(R.string.s_bank, cardBank));

        t15.setText(getString(R.string.receipt_7));

        String st;
        if (payDetail.cardType == CARDTYPE.MAGNETIC.getValue()) {
            st = " (S)";
        } else if (payDetail.cardType == CARDTYPE.IC.getValue()) {
            st = " (I)";
        } else if (payDetail.cardType == CARDTYPE.CONTACTLESS.getValue()) {
            st = " (C)";
        } else {
            st = " (M)";
        }

        //增加借贷记卡标识 1:借记卡 2:贷记卡 3:外卡
        String payType = payDetail.payType;
        if (!TextUtils.isEmpty(payType)) {
            if (payType.equals("1")) {
                st = st + getString(R.string.paytype_debit_card);
            } else if (payType.equals("2")) {
                st = st + getString(R.string.paytype_credit_card);
            } else if (payType.equals("3")) {
                st = st + getString(R.string.paytype_outside_card);
            }
        }

        String cardStr;
        if (payDetail.transactionType == 4) {
            if (SystemParamsOperation.getInstance().getSystemParamsSettings().isShieldAuthorizationCard()) {
                cardStr = NumberUtil.intercept(payDetail.CardNo);
            } else {
                cardStr = payDetail.CardNo;
            }
        } else {
            cardStr = NumberUtil.intercept(payDetail.CardNo);
        }

        t17.setText(cardStr + st);

        String transDate;
        String transTime;
        if (TextUtils.isEmpty(payDetail.TradeDate)) {
            transDate = "";
        } else {
            transDate = payDetail.TradeDate.substring(0, 2) + "/" + payDetail.TradeDate.substring(2, 4);
        }

        if (TextUtils.isEmpty(payDetail.TradeTime)) {
            transTime = "";
        } else {
            transTime = payDetail.TradeTime.substring(0, 2) + ":" + payDetail.TradeTime.substring(2, 4) + ":" + payDetail.TradeTime.substring(4, 6);
        }

        String EXPDate = " ";
        if (!TextUtils.isEmpty(payDetail.EXPDate)) {
            EXPDate = ("20" + payDetail.EXPDate.substring(0, 2) + "/" + payDetail.EXPDate.substring(2, 4));
        }
        String prepareData = getString(R.string.receipt_12) + SystemDateTime.getYYYY() + "/" + transDate + " " + transTime;
        t18.setText(prepareData);
        t20.setText(getString(R.string.receipt_8) + EXPDate);


        String typeC = "";


        if (isPrintEnglish) {
            switch (payDetail.transactionType) {
                case 4:
                case 5:
                case 6:
                case 7:
                case 1:
                case 2:
//                case "24":
                case 3:
                    typeC = payDetail.transType + "c";
                    break;
                default:
                    typeC = payDetail.transType;
                    break;
            }
        } else {
            typeC = payDetail.transType;
        }

        sb.append(getString(R.string.make7, TransType.getName(typeC)));
        t22.setText(sb.toString());
        sb.setLength(0);


        String type = "";

        switch (payDetail.transactionType) {
            case 4:
            case 5:
            case 6:
            case 7:
            case 1:
            case 2:
//                case "24":
            case 3:
                type = payDetail.transType + "e";
                break;
            default:
                type = payDetail.transType;
                break;
        }

        if (isPrintEnglish) {
            t23.setText(TransType.getName(type));
        } else {
            t23.setVisibility(GONE);
        }

        String receipt_10 = getString(R.string.receipt_10);
        String receipt_11 = getString(R.string.receipt_11);

        t25.setText(receipt_11 + payDetail.referNo);
        t27.setText(receipt_10 + payDetail.BathNo);


        String receipt_14 = getString(R.string.receipt_14);
        String receipt_15 = getString(R.string.receipt_15);


        t29.setText(receipt_14 + payDetail.authNo);
        t31.setText(receipt_15 + payDetail.voucherNo);


        String receipt_16 = getString(R.string.receipt_16);
        long amount;
        if (payDetail.transactionType == 2
                || payDetail.transactionType == 3 || payDetail.transactionType == 7 || payDetail.transactionType == 5) {
            if (SystemParamsOperation.getInstance().getSystemParamsSettings().isPrintNegative()) {
                amount = payDetail.amount * -1;
            } else {
                amount = payDetail.amount;
            }
        } else {
            amount = payDetail.amount;
        }

        t33.setText(receipt_16);

        t34.setText(CurrencyInfo.getName(payDetail.currencyCode) + " " +
                String.format(Locale.getDefault(), "%.2f", amount / 100.0));

        if (!TextUtils.isEmpty(payDetail.cardHolderName)) {
            tCardholderName.setText(getString(R.string.receipt_24) + payDetail.cardHolderName);
        } else {
            tCardholderName.setVisibility(View.INVISIBLE);
        }
        String receipt_17 = getString(R.string.receipt_17);

        t36.setText(receipt_17);

        if (payDetail.getTransactionType() == 2) {
            //消费撤销
            String temp = isPrintEnglish ? getString(R.string.pay_voucher_e) : getString(R.string.pay_voucher);
            original_flag.setText(temp + payDetail.getOriginalPOSNum());
        } else if (payDetail.getTransactionType() == 3) {
            //退货
            String temp = isPrintEnglish ? getString(R.string.original_refer_no_e) : getString(R.string.original_refer_no);
            original_flag.setText(temp + payDetail.getOriginalReferNo());
        } else {
            original_flag.setVisibility(GONE);
        }

        String againPrint = isPrintEnglish ? getString(R.string.again_print_e) : getString(R.string.again_print);

        t38.setText(againPrint);


        if ((payDetail.cardType == CARDTYPE.IC.getValue() || payDetail.cardType == CARDTYPE.CONTACTLESS.getValue()) && payDetail.getTransactionType() != 3) {
            t39.setVisibility(VISIBLE);
            t40.setVisibility(VISIBLE);
            t41.setVisibility(VISIBLE);
            t42.setVisibility(VISIBLE);
            t43.setVisibility(VISIBLE);
            t44.setVisibility(VISIBLE);
            t45.setVisibility(VISIBLE);
            t46.setVisibility(VISIBLE);
            t39.setText(getString(R.string.arqc) + payDetail.getArqC());
            t43.setText(getString(R.string.aid) + payDetail.getAID());
            t40.setText(getString(R.string.tvr) + payDetail.getTVR());
            t44.setText(getString(R.string.atc) + payDetail.getATC());
            t41.setText(getString(R.string.paydetail_app_lable) + payDetail.getAppLabel());
            t45.setText(getString(R.string.paydetail_app_name) + payDetail.getAppName());
            t42.setText(getString(R.string.tc) + payDetail.getTC());
            t46.setText(getString(R.string.tsi) + payDetail.getTSI());
        } else {
            t39.setVisibility(GONE);
            t40.setVisibility(GONE);
            t41.setVisibility(GONE);
            t42.setVisibility(GONE);
            t43.setVisibility(GONE);
            t44.setVisibility(GONE);
            t45.setVisibility(GONE);
            t46.setVisibility(GONE);
        }


        if (isPrintEnglish) {
            t4.setVisibility(VISIBLE);
            t6.setVisibility(VISIBLE);
            t8.setVisibility(VISIBLE);
            t10.setVisibility(VISIBLE);
            t12.setVisibility(VISIBLE);
            t14.setVisibility(VISIBLE);
            t16.setVisibility(VISIBLE);
            t19.setVisibility(VISIBLE);
            t21.setVisibility(VISIBLE);
            t24.setVisibility(VISIBLE);
            t26.setVisibility(VISIBLE);
            t28.setVisibility(VISIBLE);
            t30.setVisibility(VISIBLE);
            t32.setVisibility(VISIBLE);
            t35.setVisibility(VISIBLE);
            t37.setVisibility(VISIBLE);
            t48.setVisibility(VISIBLE);
            t50.setVisibility(VISIBLE);
            t52.setVisibility(VISIBLE);
        } else {
            t4.setVisibility(GONE);
            t6.setVisibility(GONE);
            t8.setVisibility(GONE);
            t10.setVisibility(GONE);
            t12.setVisibility(GONE);
            t14.setVisibility(GONE);
            t16.setVisibility(GONE);
            t15.setText(t15.getText() + ":");
            t19.setVisibility(GONE);
            t21.setVisibility(GONE);
            t24.setVisibility(GONE);
            t26.setVisibility(GONE);
            t28.setVisibility(GONE);
            t30.setVisibility(GONE);
            t32.setVisibility(GONE);
            t35.setVisibility(GONE);
            t37.setVisibility(GONE);
            t48.setVisibility(GONE);
            t50.setVisibility(GONE);
            t52.setVisibility(GONE);
        }

        //是否免密
        boolean isFreePwd = payDetail.isFreePWD;
        //是否免签
        boolean isFreeSign = payDetail.isFreeSign;
        long noPswLimit = QPSParamsOperation.getInstance().getQPSParamsSettings().getQpsParamNeedNoPswLimit();
        long noSignLimit = QPSParamsOperation.getInstance().getQPSParamsSettings().getQpsParamNeedNoSignLimit();
        no_Psw_Sign.setVisibility(VISIBLE);

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) no_Psw_Sign.getLayoutParams();
        String receipt_18 = getString(R.string.receipt_18);
        if (payDetail.isFreeSign) {
            t47.setVisibility(GONE);
            t48.setVisibility(GONE);
            esign_iv.setVisibility(View.GONE);
            t49.setVisibility(View.GONE);
            t50.setVisibility(View.GONE);
            lp.setMargins(0, 16, 0, 0);
        } else {
            lp.setMargins(0, 80, 0, 0);
            t47.setVisibility(VISIBLE);
            t48.setVisibility(VISIBLE);
            esign_iv.setVisibility(View.VISIBLE);
            t47.setText(receipt_18);
            String receipt_19 = getString(R.string.receipt_19);
            t49.setText(receipt_19);
            PrintController mPrintController = new PrintController();
            if (mPrintController.isSupportESignature() &&
                    payDetail.getESignHexData() != null && payDetail.getESignHexData().length() > 0) {
                try {
                    JbigCodec jbigCodec = JbigCodecFactory.getJbigCodec(JbigCodecFactory.CODEC.JNI_CODEC);
                    String jBigHex = payDetail.getESignHexData();
                    Bitmap[] bitmaps = jbigCodec.decode(Utils.hexStr2Bytes(jBigHex));
                    Bitmap sign = bitmaps[0];
                    esign_iv.setImageBitmap(sign);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        String hotLine = getString(R.string.hotLine);
        String str = SalesSlipPrintSettingsOperation.getInstance().getSalesSlipPrintSettings().getHotLine();
        if (TextUtils.isEmpty(str)) {
            str = " ";
        }
        if (salesSlipPrintSettings.isPrintChannelInfo()) {
            if (!Configs.getInstance().HIDE_HOT_LINE()) {
                t51.setVisibility(View.VISIBLE);
                t52.setVisibility(View.VISIBLE);
                t52.setText(str);
            } else {
                t51.setVisibility(View.GONE);
                t52.setVisibility(View.GONE);
            }
            if (TextUtils.isEmpty(Configs.getInstance().WEBSITE())) {
                t53.setVisibility(View.GONE);
                t54.setVisibility(View.GONE);
            } else {
                t53.setVisibility(View.VISIBLE);
                t54.setText(Configs.getInstance().WEBSITE());
            }
        } else {
            t51.setVisibility(View.GONE);
            t52.setVisibility(View.GONE);
            t53.setVisibility(View.GONE);
            t54.setVisibility(View.GONE);
        }


        if (isFreeSign) {
            if (isFreePwd && isFreeSign) {
                long limit = noPswLimit < noSignLimit ? noPswLimit : noSignLimit;
                //免密免签
                no_Psw_Sign.setText("\n" + String.format(getString(R.string.noPsw_noSign_flag), MoneyUtils.longCent2DoubleMoneyStr(limit))
                        + "," + qpsSettingController.getNoPswNoSignText());
            } else if (!isFreePwd && isFreeSign) {
                //非免密但免签
                no_Psw_Sign.setText("\n" + String.format(getString(R.string.noPsw_noSign_flag), MoneyUtils.longCent2DoubleMoneyStr(noSignLimit))
                        + "," + qpsSettingController.getNoSignText());
            }
        } else if (isFreePwd && !isFreeSign) {
            //免密不免签
            no_Psw_Sign.setText("\n" + String.format(getString(R.string.noPsw_noSign_flag), MoneyUtils.longCent2DoubleMoneyStr(noPswLimit))
                    + "," + qpsSettingController.getNoPwdText());
        } else {
            no_Psw_Sign.setVisibility(View.INVISIBLE);
        }
    }


    private void printHead() {
        String title = " ";
        TextView textView = (TextView) view.findViewById(R.id.textView);

        if (salesSlipPrintSettings.isPrintChannelInfo()) {
            switch (salesSlipPrintSettings.getRise()) {
                case 2:
                    headLogo.setVisibility(View.VISIBLE);
                    textView.setVisibility(View.GONE);
                    headLogo.setImageBitmap(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.abc));
                    break;
                case 0:
                    headLogo.setVisibility(View.GONE);
                    textView.setVisibility(View.VISIBLE);
                    if (TextUtils.isEmpty(salesSlipPrintSettings.getRiseString())) {
                        sspsOperation.saveRiseString(" ");
                    }
                    title = getString(R.string.receipt_1, salesSlipPrintSettings.getRiseString());
                    showHeadTitle(textView, title);
                    break;
                case 1:
                    headLogo.setVisibility(View.GONE);
                    textView.setVisibility(View.VISIBLE);
                    title = getString(R.string.receipt_1, getString(R.string.receipt_title));
                    showHeadTitle(textView, title);
                    break;
            }
        } else {
            headLogo.setVisibility(View.GONE);
            textView.setVisibility(View.VISIBLE);
            title = getString(R.string.receipt_1, getString(R.string.receipt_title));
            showHeadTitle(textView, title);
        }
    }

    private void showHeadTitle(TextView textView, String title) {
        if (sspsOperation.getSalesSlipPrintSettings().isSalesSlipPrintEnglish()) {
            textView.setText(title + "\n" + getString(R.string.receipt_1_e));
        } else {
            textView.setText(title);
        }
    }

    private String getString(int id) {
        return mContext.getString(id);
    }

    private String getString(int resId, Object... formatArgs) {
        return mContext.getString(resId, formatArgs);
    }

}
